package com.wrial.mall.search.service.impl;
/*
 * @Author  Wrial
 * @Date Created in 21:12 2020/5/19
 * @Description
 */

import com.alibaba.fastjson.JSON;
import com.wrial.mall.search.config.MallElasticSearchConfig;
import com.wrial.mall.search.constant.EsConstant;
import com.wrial.mall.search.service.ProductSaveService;
import com.wrial.to.es.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 将数据保存到ES中
     * @param skuEsModels
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //1.给es中建立索引和其映射关系（Kibana中已经建立了）
        //2.保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            indexRequest.index(EsConstant.PRODUCT_INDEX);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, MallElasticSearchConfig.COMMON_OPTIONS);

        List<String> stringList = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());

        boolean b = bulk.hasFailures();
        log.info("ES上架完成:{},返回数据{}",stringList,bulk.toString());
        return b;


    }
}
